<?php
namespace app\rpc\lib;

use app\rpc\controllers\MyController;
use lib\redis\RedisTool;

class RpcLib {

    protected $tcp_server;
    public function __construct($ip,$port)
    {
        $errno='';
        $errstr='';
        $this->tcp_server = stream_socket_server("tcp://{$ip}:{$port}", $errno, $errstr);
        if (!$this->tcp_server) {
            exit("{$errno} : {$errstr} \n");
        }
        while (true) {
            $client = stream_socket_accept($this->tcp_server);
            stream_set_timeout($client,5);
            if ($client) {
                //一次性读取服务
                $buf = fread($client, 2048);
                $data = json_decode($buf,1);
                //强行定义为controllers目录下
                $class_name = '\app\rpc\controllers\\'.$data['service'];
                $action_name = $data['action'];
                $parameter = $data['args'];
                $class = new $class_name();
                @list($p1,$p2,$p3,$p4)=$parameter;
                $rev = $class->$action_name($p1,$p2,$p3,$p4);
                $rev = $this->resJson($rev);
                $rev = json_encode($rev);
                echo "调用结果:{$rev}\n";
                fwrite($client,$rev);
                fclose($client);
            }
        }
    }

    public function __destruct() {
        fclose($this->tcp_server);
//        RedisTool::_init()->setKey('RPC_STATE')->setString(['state'=>0,'this_time'=>date('m-d H:i')])->getReturn();
    }

    public function resJson(array $data){
        if (isset($data['code'])){
            return $data;
        }
        return ['code'=>1,'data'=>$data];
    }

}